import 'package:flutter/material.dart';
import 'package:fsharing/core/models/address.dart';
import 'package:fsharing/core/viewmodels/pages/mine/address/address_sms_model.dart';
import 'package:fsharing/core/viewmodels/pages/mine/address/address_update_model.dart';
import 'package:fsharing/core/viewmodels/view_model.dart';
import 'package:fsharing/ui/pages/mine/address/address_region_page.dart';
import 'package:fsharing/ui/widgets/background_container.dart';
import 'package:fsharing/ui/widgets/count_down_text.dart';
import 'package:fsharing/ui/widgets/round_back_button.dart';
import 'package:oktoast/oktoast.dart';
import 'package:provider/provider.dart';

class AddressEditPage extends StatelessWidget {
  final Address address;

  AddressEditPage({
    Key key,
    @required this.address,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        ChangeNotifierProvider(
          create: (context) => AddressUpdateModel(Provider.of(context, listen: false), address),
        ),
        ChangeNotifierProvider(
          create: (context) => AddressSmsModel(Provider.of(context, listen: false)),
        )
      ],
      child: BackgroundContainer(
        child: Consumer<AddressUpdateModel>(
          builder: (context, model, child) {
            return Form(
              child: Scaffold(
                appBar: AppBar(
                  leading: RoundBackButton(),
                  title: Text(model.address == null ? '新增地址' : '修改地址'),
                  actions: <Widget>[
                    Builder(
                      builder: (context) {
                        return FlatButton(
                          onPressed: () => _addressUpdate(context),
                          child: Text('保存'),
                        );
                      },
                    ),
                  ],
                ),
                body: _ScrollWidget(),
              ),
            );
          },
        ),
      ),
    );
  }

  void _addressUpdate(BuildContext context) async {
    if (Form.of(context).validate()) {
      AddressUpdateModel addressEditModel = Provider.of(context, listen: false);
      ViewState viewState = await addressEditModel.addressUpdate();
      switch (viewState) {
        case ViewState.error:
          showToast(addressEditModel.errorMessage);
          break;
        default:
          Navigator.of(context).pop(true);
          break;
      }
    }
  }
}

class _ScrollWidget extends StatelessWidget {
  const _ScrollWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    var divider = Divider(
      height: 1,
      indent: 8,
      color: Colors.black12,
    );

    var textStyle = TextStyle(
      color: Colors.black87,
      fontSize: 14,
    );

    var inputDecoration = InputDecoration(
      hintStyle: TextStyle(color: Colors.black54),
      border: InputBorder.none,
    );

    AddressUpdateModel addressEditModel = Provider.of(context, listen: false);

    return SingleChildScrollView(
      child: Container(
        decoration: BoxDecoration(
          color: Colors.white,
          borderRadius: BorderRadius.circular(10),
        ),
        margin: EdgeInsets.only(left: 12, right: 12, bottom: 12),
        child: Column(
          children: <Widget>[
            _HeaderWidget(),
            divider,
            ListTile(
              title: TextFormField(
                initialValue: addressEditModel.address?.linkMan ?? '',
                decoration: inputDecoration.copyWith(
                  hintText: '收货人',
                ),
                style: textStyle,
                onChanged: (value) {
                  addressEditModel.linkMan = value;
                },
                validator: (value) {
                  return value.isNotEmpty ? null : '请输入收货人';
                },
              ),
            ),
            divider,
            ListTile(
              title: TextFormField(
                initialValue: addressEditModel.address?.contactPhone ?? '',
                decoration: inputDecoration.copyWith(
                  hintText: '手机号码',
                ),
                style: textStyle,
                keyboardType: TextInputType.phone,
                onChanged: (value) {
                  addressEditModel.contactPhone = value;
                },
                validator: (value) {
                  return value.isNotEmpty ? null : '请输入手机号码';
                },
              ),
              trailing: Consumer<AddressSmsModel>(
                builder: (context, model, child) {
                  switch (model.viewState) {
                    case ViewState.busy:
                      return FlatButton(
                        onPressed: null,
                        child: SizedBox(
                          width: 12,
                          height: 12,
                          child: CircularProgressIndicator(),
                        ),
                      );
                    case ViewState.success:
                      return FlatButton(
                        onPressed: null,
                        child: CountDownText(
                          function: () {
                            AddressSmsModel model = Provider.of(context, listen: false);
                            model.viewState = ViewState.idle;
                          },
                          style: textStyle.copyWith(
                            color: Colors.grey,
                          ),
                        ),
                      );
                    default:
                      return FlatButton(
                        onPressed: () => _reqCode(context),
                        child: Text(
                          '获取验证码',
                          style: textStyle,
                        ),
                      );
                  }
                },
              ),
            ),
            divider,
            ListTile(
              title: TextFormField(
                decoration: inputDecoration.copyWith(
                  hintText: '验证码（未修改手机号码，则无须填写）',
                ),
                style: textStyle,
                onChanged: (value) {
                  addressEditModel.verifyCode = value;
                },
                validator: (value) {
                  AddressUpdateModel model = Provider.of(context, listen: false);
                  return model.address?.contactPhone == model.contactPhone || value.isNotEmpty
                      ? null
                      : '请输入验证码';
                },
              ),
            ),
            divider,
            ListTile(
              title: Text(
                addressEditModel.provCityCounty ?? '所在地区',
                style: textStyle,
              ),
              trailing: Icon(
                Icons.keyboard_arrow_right,
                color: Colors.grey,
              ),
              onTap: () async {
                var result = await Navigator.of(context).pushNamed(
                  '/address/region',
                  arguments: AddressRegionArgs(0, null),
                );
                debugPrint('result = $result');
                if (result != null) {
                  AddressUpdateModel addressEditModel = Provider.of(context, listen: false);
                  addressEditModel.mapEntry = result;
                }
              },
            ),
            divider,
            ListTile(
              title: TextFormField(
                initialValue: addressEditModel.address?.detailAddress ?? '',
                decoration: inputDecoration.copyWith(
                  hintText: '详细地址：如街道、门牌号、小区、楼栋号、单元室等',
                ),
                style: textStyle,
                maxLines: 3,
                onChanged: (value) {
                  addressEditModel.detailAddress = value;
                },
                validator: (value) {
                  return value.isNotEmpty ? null : '请输入详细地址';
                },
              ),
            ),
            divider,
            SwitchListTile(
              value: addressEditModel.defaulted,
              onChanged: (value) {
                addressEditModel.defaulted = value;
              },
              title: Text(
                '设为默认',
                style: textStyle,
              ),
            ),
          ],
        ),
      ),
    );
  }

  void _reqCode(BuildContext context) async {
    AddressUpdateModel addressEditModel = Provider.of(context, listen: false);
    AddressSmsModel addressSmsModel = Provider.of(context, listen: false);
    ViewState viewState = await addressSmsModel.addressSms(addressEditModel.contactPhone);
    switch (viewState) {
      case ViewState.error:
        showToast(addressSmsModel.errorMessage);
        break;
      default:
        // 更新code
        addressEditModel.encryptedCode = addressSmsModel.data;
        showToast('发送成功');
        break;
    }
  }
}

class _HeaderWidget extends StatelessWidget {
  const _HeaderWidget({
    Key key,
  }) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(
      alignment: Alignment.centerLeft,
      decoration: BoxDecoration(
        image: DecorationImage(
          image: AssetImage('assets/images/cart/img_store.png'),
          fit: BoxFit.fill,
        ),
      ),
      height: 45,
      padding: EdgeInsets.only(left: 12),
      child: Text('收货地址'),
    );
  }
}
